import React, { useState } from 'react';
import { Card, Typography, Form, Select, Button, Upload, message } from 'antd';
import { DownloadOutlined, InboxOutlined, RetweetOutlined } from '@ant-design/icons';
import { toolAPI } from '../utils/api';

const { Title } = Typography;
const { Option } = Select;
const { Dragger } = Upload;

const PhotoProcessPage = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [processedImageUrl, setProcessedImageUrl] = useState(null);
  const [originalImageUrl, setOriginalImageUrl] = useState(null);
  const [file, setFile] = useState(null);
  const [fileList, setFileList] = useState([]);

  // 支持的背景颜色选项
  const backgroundColors = [
    { value: 'red', label: '红底' },
    { value: 'white', label: '白底' },
    { value: 'blue', label: '蓝底' }
  ];

  // 支持的文件类型
  const supportedFileTypes = ['jpg', 'jpeg', 'png'];

  // 处理文件上传
  const handleUpload = (uploadFile) => {
    console.log('handleUpload函数被调用');
    console.log('接收到的文件对象:', uploadFile);
    
    // 检查文件是否存在
    if (!uploadFile) {
      console.log('未接收到文件');
      return false;
    }
    
    // 检查文件类型
    const fileExtension = uploadFile.name.split('.').pop().toLowerCase();
    console.log('文件扩展名:', fileExtension);
    if (!supportedFileTypes.includes(fileExtension)) {
      message.error('不支持的文件类型，请上传JPG、JPEG或PNG格式的图片');
      return false;
    }

    // 显示预览
    const reader = new FileReader();
    reader.onload = (e) => {
      setOriginalImageUrl(e.target.result);
      // 更新文件列表，显示缩略图
      const newFileList = [{
        uid: uploadFile.uid,
        name: uploadFile.name,
        status: 'done',
        url: e.target.result
      }];
      setFileList(newFileList);
    };
    reader.readAsDataURL(uploadFile);

    setFile(uploadFile);
    setProcessedImageUrl(null); // 清除之前的处理结果
    message.success(`已选择文件: ${uploadFile.name}`);
    return false; // 阻止自动上传
  };

  // 处理表单提交
  const handleSubmit = async (values) => {
    if (!file) {
      message.error('请先上传照片');
      return;
    }

    const backgroundColor = values.backgroundColor;
    if (!backgroundColor) {
      message.error('请选择照片底色');
      return;
    }

    setLoading(true);

    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('backgroundColor', backgroundColor);

      const response = await toolAPI.batchChangePhotoBackground(formData);

      // 处理响应，创建下载链接
      console.log('响应数据:', response);
      // 由于响应拦截器对blob类型返回完整response对象，直接使用response.data
      const blob = new Blob([response.data], {
        type: 'image/jpeg'
      });
      console.log('创建的Blob:', blob);
      const url = window.URL.createObjectURL(blob);
      console.log('创建的URL:', url);
      setProcessedImageUrl(url);
      console.log('URL已设置到processedImageUrl状态'); // React状态更新是异步的，这里不能立即获取新值
      message.success('证件照背景处理成功！');
    } catch (error) {
      console.error('证件照处理失败:', error);
      message.error(`处理失败: ${error.response?.data?.error || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 处理下载
  const handleDownload = () => {
    if (processedImageUrl) {
      const link = document.createElement('a');
      link.href = processedImageUrl;
      // 生成文件名，包含原始文件名和背景色
      const originalFileName = file?.name?.substring(0, file.name.lastIndexOf('.')) || 'processed';
      const backgroundColor = form.getFieldValue('backgroundColor') || 'unknown';
      link.download = `${originalFileName}_${backgroundColor}_background.jpg`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  // 重置表单
  const handleReset = () => {
    form.resetFields();
    setFile(null);
    setFileList([]);
    setOriginalImageUrl(null);
    setProcessedImageUrl(null);
  };

  return (
    <Card className="tool-page" style={{ width: '60vw', height: `600px`, margin: '0 auto', overflow: 'auto' }}>
      <Title level={2}>证件照背景处理</Title>
      
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        className="form-section"
        style={{ height: 'auto', minHeight: '300px' }}
      >
        <Form.Item 
          label="上传照片"
          required
          className="form-section"
        >
          <Dragger
            accept=".jpg,.jpeg,.png"
            beforeUpload={handleUpload}
            fileList={fileList}
            showUploadList={{
              showRemoveIcon: true
            }}
            disabled={loading}
            onRemove={() => {
              setFileList([]);
              setFile(null);
              setOriginalImageUrl(null);
              setProcessedImageUrl(null);
              return true;
            }}
            style={{ height: '250px' }}
          >
            {fileList.length === 0 ? (
              <>
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">点击或拖拽照片到此处上传</p>
                <p className="ant-upload-hint">
                  支持的图片格式: JPG, JPEG, PNG
                </p>
              </>
            ) : (
              <div style={{ textAlign: 'center', marginTop: '48px', marginBottom: '48px' }}>
                <p className="ant-upload-text">已上传照片，可继续上传替换或点击移除按钮重新上传</p>
              </div>
            )}
          </Dragger>
        </Form.Item>

        <Form.Item
          label="选择照片底色"
          name="backgroundColor"
          rules={[{ required: true, message: '请选择照片底色' }]}
          className="form-section"
        >
          <Select 
            placeholder="请选择照片底色"
            disabled={loading}
            style={{ width: '100%', height: '40px' }}
          >
            {backgroundColors.map(color => (
              <Option key={color.value} value={color.value}>
                <span style={{ 
                  display: 'inline-block', 
                  width: '16px', 
                  height: '16px', 
                  backgroundColor: color.value,
                  marginRight: '8px',
                  border: '1px solid #d9d9d9'
                }} />
                {color.label}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <div className="button-group" style={{ marginTop: '20px' }}>
          <Button type="primary" htmlType="submit" loading={loading} icon={<RetweetOutlined />}>
            处理照片
          </Button>
          <Button onClick={handleReset} disabled={loading}>
            重置
          </Button>
        </div>
      </Form>

      {/* 处理后照片预览区域 */}
      {processedImageUrl && (
        <div className="result-section" style={{ marginTop: '40px' }}>
          <Title level={3}>处理结果</Title>
          <div className="image-preview-container" style={{ height: 'auto' }}>
            <div className="image-preview-item" style={{ height: 'auto' }}>
              <Typography.Text strong>处理后照片:</Typography.Text>
              <div className="image-wrapper" style={{ height: '300px', display: 'flex', justifyContent: 'center', alignItems: 'center', margin: '20px 0' }}>
                <img 
                  src={processedImageUrl} 
                  alt="处理后照片" 
                  className="preview-image"
                  style={{ maxHeight: '100%', maxWidth: '100%', objectFit: 'contain' }}
                />
              </div>
              <Button 
                type="primary" 
                icon={<DownloadOutlined />}
                onClick={handleDownload}
                style={{ marginTop: '16px', height: '40px' }}
              >
                下载照片
              </Button>
            </div>
          </div>
        </div>
      )}
    </Card>
  );
};

export default PhotoProcessPage;